﻿using AutoMapper;
using MaterialManagement.API.Application.Command.MesWorkOrder;
using MaterialManagement.Domain.MesWorkOrder;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Implement;
using MediatR;
using ProductionLine.Domain.BOM;

namespace MaterialManagement.API.Application.Handler.MesWorkOrder
{
    public class CreateBOMHandler : IRequestHandler<CreateBOMCommand, APIResult<int>>
    {
        private readonly DatabaseContext database;
        private readonly IMapper mapper;

        public CreateBOMHandler(DatabaseContext database,
                                IMapper mapper)
        {
            this.database = database;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(CreateBOMCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var BOM = await database.SqlSugar.Queryable<BOMInformationModel>().FirstAsync(x => x.BOMCode == request.BOMCode);
            if (BOM != null)
            {
                result.Message = "BOM编号已存在!";
                result.Code = APIEnum.Fail;
                return await Task.FromResult(result);
            }
            try
            {
                await database.SqlSugar.Ado.BeginTranAsync();
                var bomModel = mapper.Map<BOMInformationModel>(request);
                await database.SqlSugar.Insertable(bomModel).ExecuteCommandAsync();
                var material = request.BOMProductModels.Select(x => new BOMProductModel
                {
                    BOMCode = request.BOMCode,
                    MaterialCode = x.MaterialCode,
                    Quantity = x.Quantity,
                    LossRate = x.LossRate
                }).ToList();
                int r = await database.SqlSugar.Insertable(material).ExecuteCommandAsync();
                if (r > 0)
                {
                    result.Message = "添加成功";
                    result.Code = APIEnum.Ok;
                    result.Data = r;
                    BOMLogsModel logsModel = new BOMLogsModel()
                    {
                        Operator = "张三",
                        Message = "BOM添加成功",
                        OperationTime = DateTime.Now
                    };
                    await database.SqlSugar.Insertable(logsModel).ExecuteCommandAsync();
                }
                else
                {
                    result.Message = "添加失败";
                    result.Code = APIEnum.Fail;
                    result.Data = r;
                    BOMLogsModel logsModel = new BOMLogsModel()
                    {
                        Operator = "张三",
                        Message = "BOM添加失败",
                        OperationTime = DateTime.Now
                    };
                    await database.SqlSugar.Insertable(logsModel).ExecuteCommandAsync();
                }
                await database.SqlSugar.Ado.CommitTranAsync();
            }
            catch (Exception)
            {
                await database.SqlSugar.RollbackTranAsync();
                throw;
            }
            return await Task.FromResult(result);
        }
    }
}
